package cn.kw0501.tms.utils;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;

/**
 * KJ0301
 *
 * @Description :
 * @Author : Aedes
 * @Date: 2022/11/18 11:33
 */
@Slf4j
public class SmsUtil {
    private static String accessKeyId = "LTAI4G6dR2uLfBM4u3dg2c53";
    private static String accessKeySecret = "08ND01MXW1sGKj8WgBE3h5ZzPpWNyU";
    private static String signName = "Aedes商城";

    String TemplateCode = "SMS_206560024";

    /**
     * 发送短信
     * @param phone
     * @param code
     * @param typeNum
     * @return
     */
    public static boolean sendSms(String phone,String code,Integer typeNum){
        //创建客户端
        Config config = new Config();
        config.setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信对象创建失败");
            return false;
        }

        //创建发送信息请求
        String codeStr = "{\"code\":\""+code+"\"}";
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(signName).setPhoneNumbers(phone).setTemplateParam(codeStr);
        if(typeNum==1){
            request.setTemplateCode("SMS_206560024");
        }

        //通过客户端发送短信
        SendSmsResponse response = null;
        try {
            response = client.sendSms(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送创建失败");
            return false;
        }
        //验证结果并返回
        //log.info(response.toString());
        if(!response.getBody().getCode().equals("OK")){
            log.error("发送失败:"+response.getBody().getMessage());
            return false;
        }

        return true;
    }
    /**
     * 参数介绍：生成短信验证码
     * @description: 功能描述
     * @author: Aedes
     * @date: 2022/8/27 9:57
     * @return: java.lang.String
     **/
    public static String getCode(){
        return RandomUtil.randomNumbers(6);
    }

    public static void main(String[] args) {
        sendSms("18092181700",getCode(),1);
    }
}



